import React, { useState } from "react";
import { Table, Card, Button, Space, Tag, Descriptions } from "antd";
import type { ColumnsType } from "antd/es/table";
import type { EMRRecord } from "../../types/emr";
import { useNavigate } from "react-router-dom";
import Layout from "../../components/Layout";

interface PatientWithEMR {
  id: string;
  name: string;
  emrs: EMRRecord[];
}
// mock数据
const mockPatients: PatientWithEMR[] = [
  {
    id: 'p1', name: '张三', emrs: [
      { id: 'e1', patientId: 'p1', patientName: '张三', doctorId: 'd1', doctorName: '王医生', createdAt: '2024-06-01', updatedAt: '2024-06-02', chiefComplaint: '膝关节疼', history: '近一月反复发作', physicalExam: '膝关节压痛', diagnosis: '骨关节炎', prescription: [ { drugName: '氨糖', dosage: '0.75g', usage: '口服bid', days: 30 } ] }
    ]
  },
  {
    id: 'p2', name: '李四', emrs: [
      { id: 'e2', patientId: 'p2', patientName: '李四', doctorId: 'd2', doctorName: '李医生', createdAt: '2024-06-03', updatedAt: '2024-06-03', chiefComplaint: '腰痛', history: '体力劳动后', physicalExam: '腰肌僵硬', diagnosis: '腰肌劳损', prescription: [] },
      { id: 'e3', patientId: 'p2', patientName: '李四', doctorId: 'd2', doctorName: '李医生', createdAt: '2024-06-05', updatedAt: '2024-06-05', chiefComplaint: '复诊', history: '-', physicalExam: '-', diagnosis: '好转', prescription: [] }
    ]
  }
];

const EMRList: React.FC = () => {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const navigate = useNavigate();
  // Table columns
  const columns: ColumnsType<PatientWithEMR> = [
    {
      title: "患者姓名",
      dataIndex: "name",
      width: 120,
    },
    {
      title: "病历数",
      dataIndex: "emrs",
      render: emrs => <Tag color='blue'>{emrs.length}</Tag>,
      width: 90,
    },
    {
      title: "操作",
      dataIndex: "id",
      render: (id, row) => <Button type="link" onClick={()=>navigate(`/doctor/emr/add?patientId=${id}`)}>新增病历</Button>,
      width: 100,
    }
  ];
  // 展开行病历
  const expandedRowRender = (row: PatientWithEMR) => (
    <Table
      columns={[
        { title: '主诉', dataIndex: 'chiefComplaint', width: 120 },
        { title: '诊断', dataIndex: 'diagnosis', width: 160 },
        { title: '开具时间', dataIndex: 'createdAt', width: 120 },
        { title: '操作', dataIndex: 'id', width: 100, render: (eid) => <Button type='link' onClick={()=>navigate(`/doctor/emr/${eid}`)}>详情</Button> },
      ]}
      dataSource={row.emrs}
      rowKey='id'
      pagination={false}
      size='small'
    />
  );
  return (
    <Layout title="电子病历管理">
      <Card>
      <Table
        columns={columns}
        dataSource={mockPatients.slice((page-1)*pageSize, page*pageSize)}
        rowKey='id'
        expandable={{ expandedRowRender }}
        pagination={{ current: page, pageSize, total: mockPatients.length, showSizeChanger: true, onChange(pg,size){ setPage(pg); setPageSize(size||10); } }}
      />
      </Card>
    </Layout>
  );
};
export default EMRList;
